<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="650px" destroyOnClose>
    <BasicForm @register="registerForm" >
    </BasicForm>
  
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref} from 'vue';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {BasicForm, useForm} from '/@/components/Form/index';

import {formSchema} from '../template.data';
import {getTemplate, saveOrUpdateTemplate} from '../template.api';
import {useMessage} from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);

//表单配置
const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  schemas: formSchema,
  labelWidth: 90,
  showActionButtonGroup: false,
  labelCol: {
    xs: { span: 4 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
});
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //重置表单
  await resetFields();
  try {
    console.log('data', data);
    
    setDrawerProps({ confirmLoading: true })
    isUpdate.value = !!data?.isUpdate;
    const isShowSelectTask = data?.isShowSelectTask;

    if (unref(isUpdate)) {
      // 获取详情
      const record = await getTemplate({ id: data.record.id })
      //表单赋值
      await setFieldsValue({ ...record });
    } else {
      await setFieldsValue({ 
        isShowSelectTask: isShowSelectTask === undefined ? true : isShowSelectTask, 
        taskId: data.taskId
      });
    }
  } finally {
    setDrawerProps({ confirmLoading: false })
  }
});

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增模板' : '编辑模板'));

//表单提交事件
async function handleSubmit(v) {
  try {
    let values = await validate();
    values = {...values, templateConfig: JSON.stringify({}) }
    console.log("form: ", values)
    setDrawerProps({ confirmLoading: true });

    //提交表单
    await saveOrUpdateTemplate({
      ...values, 
    }, isUpdate.value);
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit('success');
    createMessage.success(`${title.value}成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>

<style lang="less"> 

.select-channel {
  color: #40a9ff;
  margin-left: 1px;
  cursor: pointer;
  font-size: 14px;
}
</style>
